import React, { useEffect } from 'react';
import { useRequest } from '@/hooks';
import wfc from '@/chat/wfc/client/wfc';
import Config from '@/chat/config.js';
import vvChat from '@/chat/vv-chat';
import { connect } from 'umi';
import { get } from 'lodash';
import { IMLogin } from './services';

/**
 * IM 消息订阅
 * stomp为true时采用的是自建socket的方式
 */
const IM = ({ stomp, user }) => {
    const { userCode, mobile, email, employeeName: displayName } = JSON.parse(localStorage.getItem('user') || '{}');
    const { avatarFile = [] } = JSON.parse(localStorage.getItem('loginInfo') || '{}');

    // 登录im
    const { data, run } = useRequest(params => IMLogin(params), {
        manual: true
    });

    useEffect(() => {
        if (userCode) {
            run({
                deviceName: 'web',
                userCode,
                clientId: wfc.getClientId(),
                platform: Config.getWFCPlatform(),
                mobile,
                email,
                displayName,
                portrait: get(avatarFile, '[0].keyName', '')
            });
        }
    }, [run, userCode]);

    useEffect(() => {
        if (stomp && user) {
            vvChat.connection(user, new Date().getTime());
        }

        return () => {
            if (stomp) {
                vvChat.disconnect();
            }
        };
    }, [stomp, user]);

    useEffect(() => {
        if (data && !stomp) {
            const { code, data: res } = data;
            if (code === 10000) {
                const { userId, token, routeIp } = res;
                if (userId && token && routeIp) {
                    wfc.init([{ IM_SERVER_HOST: routeIp }]); // IM初始化
                    wfc.connect(userId, token);
                }
            }
        }

        return () => {
            if (!stomp) {
                wfc.disconnect();
            }
        };
    }, [data, stomp]);

    return <></>;
};

export default connect(({ user }) => ({ user: user?.currentUser?.employeeCode }))(IM);
